# -*- coding: utf-8 -*-
# 北梦测教育
# 课程咨询加微信：xiaobeiceshi
import os

import pymysql
from pymysql.cursors import DictCursor
import logging
from apiException.custom_exception import *
from utils.decorator import singleton



@singleton
class Database:
    def __init__(self):
        # 因为只在内部访问这个self.__db
        # 所以可以将其设置为私有属性
        self.__db = self.__get_connection()

    @staticmethod
    def __get_connection():
        # 创建连接对象的方法
        # __data = GetConfig().get_database_data("test_base_url")
        __data = eval(os.environ["DATABASE"])
        print(__data)
        try:
            conn = pymysql.Connect(
                # host=DB_HOST,
                # port=DB_PORT,
                # database=DB_NAME,
                # user=DB_USER,
                # password=DB_PASSWORD,
                # charset="utf8",
                **__data,
                autocommit=True
            )
            return conn
        except Exception as e:
            logging.error(f"数据库连接失败，错误信息: {e}")
            raise DatabaseException()

    def get_one(self, sql):
        try:
            if self.__db:
                # 执行SQL查询并返回结果
                with self.__db.cursor(DictCursor) as cur:
                    cur.execute(sql)
                    return cur.fetchone()
        except Exception as e:
            logging.error(f"数据库查询失败，错误信息: {e}")
            raise GetDataException()

    def execute_sql(self, *sqls):  # *参数表示可变参数，打包成一个元组
        try:
            # 执行SQL语句，不需要返回值--用于删除或修改
            if self.__db:
                with self.__db.cursor(DictCursor) as cur:
                    for sql in sqls:
                        cur.execute(sql)
        except Exception as e:
            logging.error(f"数据库修改或删除失败，错误信息: {e}")
            raise ExecuteSqlException()

    def close(self):
        """关闭数据库连接的方法"""
        self.__db.close()

    # 配合with使用的，在with执行的时候调用
    def __enter__(self):
        return self

    # 配合with使用的，在退出with代码块的时候调用
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()



if __name__ == '__main__':
    db = Database()
    print(db)
    db2 = Database()
    print(db2)
    # SQL1 = 'UPDATE base_data_product_brand set NAME = "大米" where code = 001'
    SQL2 = 'select * from base_data_customer'
    # db.execute_sql(SQL1)
    print(db.get_one(SQL2))



